// 价格策略管理模块
const React = window.React;
const ReactDOM = window.ReactDOM;
const { message, Modal, notification } = window.antd;

// 价格策略类型枚举
const PriceStrategyType = {
    TIME_PERIOD: 'time_period',    // 时段价格
    HOLIDAY: 'holiday',            // 节假日价格
    MEMBER_DISCOUNT: 'member',     // 会员折扣
    PROMOTION: 'promotion'         // 促销活动
};

// 价格策略数据结构
class PriceStrategy {
    constructor(id, name, type, rules, startTime, endTime, status = true) {
        this.id = id;
        this.name = name;
        this.type = type;
        this.rules = rules;         // 价格规则配置
        this.startTime = startTime; // 策略开始时间
        this.endTime = endTime;     // 策略结束时间
        this.status = status;       // 策略状态
        this.createTime = new Date().toISOString();
        this.updateTime = new Date().toISOString();
    }
}

// 价格策略管理类
export default class PriceStrategyManager {
    constructor() {
        this.strategies = [];
        this.selectedStrategies = new Set();
        this.priceChangeHistory = [];
    }

    init() {
        // 初始化DOM元素
        this.contentWrapper = document.querySelector('.content-wrapper');
        if (!this.contentWrapper) {
            this.contentWrapper = document.createElement('div');
            this.contentWrapper.className = 'content-wrapper';
            document.querySelector('.main-container').appendChild(this.contentWrapper);
        }

        // 创建价格策略列表容器
        this.contentWrapper.innerHTML = `
            <div class="price-strategy-container">
                <div class="strategy-toolbar">
                    <div class="strategy-toolbar-info">已选择 0 个策略</div>
                    <div class="strategy-toolbar-actions">
                        <button data-action="create">新建策略</button>
                        <button data-action="delete">批量删除</button>
                        <button data-action="enable">批量启用</button>
                        <button data-action="disable">批量禁用</button>
                    </div>
                </div>
                <div class="strategy-list-content"></div>
            </div>
        `;

        // 初始化事件监听
        this.initEventListeners();

        // 加载测试数据
        this.loadTestData();
    }

    loadTestData() {
        // 添加测试数据
        this.strategies = [
            new PriceStrategy(
                1,
                '工作日午餐优惠',
                PriceStrategyType.TIME_PERIOD,
                {
                    discount: 0.9,
                    timeRange: ['11:30', '14:00'],
                    daysOfWeek: [1, 2, 3, 4, 5]
                },
                '2024-01-01',
                '2024-12-31'
            ),
            new PriceStrategy(
                2,
                '春节特惠',
                PriceStrategyType.HOLIDAY,
                {
                    discount: 1.2,
                    holidays: ['2024-02-10', '2024-02-11', '2024-02-12']
                },
                '2024-02-10',
                '2024-02-12'
            ),
            new PriceStrategy(
                3,
                'VIP会员折扣',
                PriceStrategyType.MEMBER_DISCOUNT,
                {
                    memberLevels: {
                        vip1: 0.95,
                        vip2: 0.9,
                        vip3: 0.85
                    }
                },
                '2024-01-01',
                '2024-12-31'
            )
        ];
        this.renderStrategyList();
    }

    // 初始化事件监听
    initEventListeners() {
        // 批量选择事件
        document.addEventListener('change', (e) => {
            if (e.target.matches('.strategy-select')) {
                const strategyId = e.target.closest('.strategy-card').dataset.id;
                if (e.target.checked) {
                    this.selectedStrategies.add(strategyId);
                } else {
                    this.selectedStrategies.delete(strategyId);
                }
                this.updateToolbar();
            }
        });

        // 批量操作事件
        const toolbarActions = document.querySelector('.strategy-toolbar-actions');
        if (toolbarActions) {
            toolbarActions.addEventListener('click', (e) => {
                const action = e.target.dataset.action;
                if (action) {
                    this.handleBatchAction(action);
                }
            });
        }
    }

    // 更新工具栏
    updateToolbar() {
        const info = document.querySelector('.strategy-toolbar-info');
        if (info) {
            info.textContent = `已选择 ${this.selectedStrategies.size} 个策略`;
        }
    }

    // 处理批量操作
    handleBatchAction(action) {
        switch (action) {
            case 'create':
                this.createStrategy();
                break;
            case 'delete':
                this.batchDelete();
                break;
            case 'enable':
                this.batchUpdateStatus(true);
                break;
            case 'disable':
                this.batchUpdateStatus(false);
                break;
        }
    }

    // 创建新策略
    createStrategy() {
        const formContent = React.createElement(
            'div',
            { className: 'strategy-form-container' },
            React.createElement(
                'form',
                { className: 'strategy-form' },
                React.createElement(
                    'div',
                    { className: 'form-item' },
                    React.createElement('label', null, '策略名称'),
                    React.createElement('input', { type: 'text', name: 'name', required: true })
                ),
                React.createElement(
                    'div',
                    { className: 'form-item' },
                    React.createElement('label', null, '策略类型'),
                    React.createElement(
                        'select',
                        { name: 'type', required: true },
                        React.createElement('option', { value: PriceStrategyType.TIME_PERIOD }, '时段价格'),
                        React.createElement('option', { value: PriceStrategyType.HOLIDAY }, '节假日价格'),
                        React.createElement('option', { value: PriceStrategyType.MEMBER_DISCOUNT }, '会员折扣'),
                        React.createElement('option', { value: PriceStrategyType.PROMOTION }, '促销活动')
                    )
                ),
                React.createElement(
                    'div',
                    { className: 'form-item' },
                    React.createElement('label', null, '开始时间'),
                    React.createElement('input', { type: 'datetime-local', name: 'startTime', required: true })
                ),
                React.createElement(
                    'div',
                    { className: 'form-item' },
                    React.createElement('label', null, '结束时间'),
                    React.createElement('input', { type: 'datetime-local', name: 'endTime', required: true })
                ),
                React.createElement(
                    'div',
                    { className: 'form-item' },
                    React.createElement('label', null, '价格调整'),
                    React.createElement('input', { type: 'number', name: 'adjustment', step: '0.01', required: true }),
                    React.createElement(
                        'select',
                        { name: 'adjustmentType' },
                        React.createElement('option', { value: 'percent' }, '百分比'),
                        React.createElement('option', { value: 'fixed' }, '固定金额')
                    )
                )
            )
        );
        
        Modal.confirm({
            title: '创建价格策略',
            content: formContent,
            width: 600,
            onOk: () => {
                const form = document.querySelector('.strategy-form');
                const formData = new FormData(form);
                const data = Object.fromEntries(formData.entries());
                
                if (!this.validateStrategyForm(data)) {
                    return Promise.reject();
                }

                const strategy = new PriceStrategy(
                    Date.now(),
                    data.name,
                    data.type,
                    this.parseStrategyRules(data),
                    data.startTime,
                    data.endTime
                );

                this.strategies.push(strategy);
                this.renderStrategyList();
                message.success('策略创建成功');
            }
        });
    }

    // 批量删除
    batchDelete() {
        if (this.selectedStrategies.size === 0) {
            message.warning('请先选择要删除的策略');
            return;
        }

        Modal.confirm({
            title: '确认删除',
            content: `确定要删除选中的 ${this.selectedStrategies.size} 个策略吗？`,
            onOk: () => {
                this.selectedStrategies.forEach(id => {
                    const index = this.strategies.findIndex(s => s.id === parseInt(id));
                    if (index !== -1) {
                        this.strategies.splice(index, 1);
                    }
                });
                this.selectedStrategies.clear();
                this.updateToolbar();
                this.renderStrategyList();
                message.success('删除成功');
            }
        });
    }

    // 批量更新状态
    batchUpdateStatus(status) {
        if (this.selectedStrategies.size === 0) {
            message.warning('请先选择要操作的策略');
            return;
        }

        this.selectedStrategies.forEach(id => {
            const strategy = this.strategies.find(s => s.id === parseInt(id));
            if (strategy) {
                strategy.status = status;
                strategy.updateTime = new Date().toISOString();

                // 记录价格变更历史
                this.priceChangeHistory.push({
                    strategyId: strategy.id,
                    strategyName: strategy.name,
                    action: status ? '启用' : '禁用',
                    timestamp: new Date().toISOString(),
                    operator: 'admin' // 实际应用中需要获取真实的操作者信息
                });
            }
        });

        this.renderStrategyList();
        message.success(`批量${status ? '启用' : '禁用'}成功`);
    }

    // 渲染策略表单
    renderStrategyForm() {
        return React.createElement(
            'form',
            { className: 'strategy-form' },
            React.createElement(
                'div',
                { className: 'form-item' },
                React.createElement('label', null, '策略名称'),
                React.createElement('input', { type: 'text', name: 'name', required: true })
            ),
            React.createElement(
                'div',
                { className: 'form-item' },
                React.createElement('label', null, '策略类型'),
                React.createElement(
                    'select',
                    { name: 'type', required: true },
                    React.createElement('option', { value: PriceStrategyType.TIME_PERIOD }, '时段价格'),
                    React.createElement('option', { value: PriceStrategyType.HOLIDAY }, '节假日价格'),
                    React.createElement('option', { value: PriceStrategyType.MEMBER_DISCOUNT }, '会员折扣'),
                    React.createElement('option', { value: PriceStrategyType.PROMOTION }, '促销活动')
                )
            ),
            React.createElement(
                'div',
                { className: 'form-item' },
                React.createElement('label', null, '开始时间'),
                React.createElement('input', { type: 'datetime-local', name: 'startTime', required: true })
            ),
            React.createElement(
                'div',
                { className: 'form-item' },
                React.createElement('label', null, '结束时间'),
                React.createElement('input', { type: 'datetime-local', name: 'endTime', required: true })
            ),
            React.createElement(
                'div',
                { className: 'form-item' },
                React.createElement('label', null, '价格调整'),
                React.createElement('input', { type: 'number', name: 'adjustment', step: '0.01', required: true }),
                React.createElement(
                    'select',
                    { name: 'adjustmentType' },
                    React.createElement('option', { value: 'percent' }, '百分比'),
                    React.createElement('option', { value: 'fixed' }, '固定金额')
                )
            )
        );
    }

    // 验证策略表单
    validateStrategyForm(formData) {
        if (!formData.name || !formData.type || !formData.startTime || !formData.endTime) {
            message.error('请填写完整的策略信息');
            return false;
        }

        const start = new Date(formData.startTime);
        const end = new Date(formData.endTime);
        if (start >= end) {
            message.error('结束时间必须晚于开始时间');
            return false;
        }

        return true;
    }

    // 解析策略规则
    parseStrategyRules(formData) {
        const rules = {
            adjustmentType: formData.adjustmentType,
            adjustment: parseFloat(formData.adjustment)
        };

        switch (formData.type) {
            case PriceStrategyType.TIME_PERIOD:
                rules.timeRange = formData.timeRange;
                rules.daysOfWeek = formData.daysOfWeek;
                break;
            case PriceStrategyType.HOLIDAY:
                rules.holidays = formData.holidays;
                break;
            case PriceStrategyType.MEMBER_DISCOUNT:
                rules.memberLevels = formData.memberLevels;
                break;
            case PriceStrategyType.PROMOTION:
                rules.conditions = formData.conditions;
                break;
        }

        return rules;
    }

    // 渲染策略列表
    renderStrategyList() {
        const listContent = document.querySelector('.strategy-list-content');
        if (!listContent) return;

        listContent.innerHTML = this.strategies.map(strategy => this.renderStrategyCard(strategy)).join('');
    }

    // 渲染策略卡片
    renderStrategyCard(strategy) {
        return `
            <div class="strategy-card" data-id="${strategy.id}">
                <input type="checkbox" class="strategy-select" ${this.selectedStrategies.has(strategy.id.toString()) ? 'checked' : ''}>
                <div class="strategy-info">
                    <h3 class="strategy-name">${strategy.name}</h3>
                    <div class="strategy-type">${this.getStrategyTypeText(strategy.type)}</div>
                    <div class="strategy-time">
                        ${new Date(strategy.startTime).toLocaleString()} - ${new Date(strategy.endTime).toLocaleString()}
                    </div>
                    <div class="strategy-rules">${this.renderStrategyRules(strategy.rules, strategy.type)}</div>
                </div>
                <div class="strategy-status ${strategy.status ? 'active' : 'inactive'}">
                    ${strategy.status ? '已启用' : '已禁用'}
                </div>
                <div class="strategy-actions">
                    <button class="edit-btn" onclick="editStrategy(${strategy.id})">编辑</button>
                    <button class="delete-btn" onclick="deleteStrategy(${strategy.id})">删除</button>
                </div>
            </div>
        `;
    }

    // 获取策略类型文本
    getStrategyTypeText(type) {
        const typeMap = {
            [PriceStrategyType.TIME_PERIOD]: '时段价格',
            [PriceStrategyType.HOLIDAY]: '节假日价格',
            [PriceStrategyType.MEMBER_DISCOUNT]: '会员折扣',
            [PriceStrategyType.PROMOTION]: '促销活动'
        };
        return typeMap[type] || '未知类型';
    }

    // 格式化星期显示
    formatDaysOfWeek(days) {
        if (!Array.isArray(days)) return '';
        const weekMap = {
            1: '周一',
            2: '周二',
            3: '周三',
            4: '周四',
            5: '周五',
            6: '周六',
            7: '周日'
        };
        return days.map(day => weekMap[day] || '').filter(Boolean).join('、');
    }

    // 渲染策略规则
    renderStrategyRules(rules, type) {
        switch (type) {
            case PriceStrategyType.TIME_PERIOD:
                return `时段：${rules.timeRange.join(' - ')}, 适用日期：${this.formatDaysOfWeek(rules.daysOfWeek)}`;
            case PriceStrategyType.HOLIDAY:
                return `节假日：${rules.holidays.join(', ')}`;
            case PriceStrategyType.MEMBER_DISCOUNT:
                return `会员等级折扣：${Object.entries(rules.memberLevels).map(([level, discount]) => `${level}: ${discount * 100}%`).join(', ')}`;
            case PriceStrategyType.PROMOTION:
                return `促销活动：${rules.conditions.map(condition => `满${condition.threshold}减${condition.discount}`).join(', ')}`;
        }
    }
}